// db.ts
import { openDB } from 'idb';

const db = await openDB('slg-app', 6, {
  upgrade(db) {

    if(db.objectStoreNames.contains('textbooks')) {
      db.deleteObjectStore('textbooks');
    }
    if(db.objectStoreNames.contains('quizzes')) {
      db.deleteObjectStore('quizzes');
    }
    if(db.objectStoreNames.contains('quizHistory')) {
      db.deleteObjectStore('quizHistory');
    }
    const textbooksObjectStore = db.createObjectStore('textbooks', { keyPath: 'chapter_title' });
    textbooksObjectStore.createIndex('book_title', 'book_title', { unique: false });

    // 存题库
    const quizObjectStore = db.createObjectStore('quizzes', { keyPath: 'id' });
    quizObjectStore.createIndex('chapterTitle', 'basic_info.chapter_title', { unique: false });

    // 存答题记录
    const answers = db.createObjectStore('quizHistory', { keyPath: 'quizTitle' });
    answers.createIndex('nextReviewAt', 'nextReviewAt');
  },
});

export default db;